package cn.itguy.mobileguard.widget;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.itguy.mobileguard.R;

import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RadioButton;
import android.widget.TextView;

public class ModeListAdapter extends BaseAdapter {

	private List<Map<String, Object>> modes = new ArrayList<Map<String, Object>>();
	
	private int selectedItemPos;
	
	public void setSelectedItemPos(int selectedItemPos) {
		this.selectedItemPos = selectedItemPos;
	}
	
	public int getSelectedItemPos() {
		return selectedItemPos;
	}

	public List<Map<String, Object>> getModes() {
		return modes;
	}

	public void setModes(List<Map<String, Object>> modes) {
		this.modes = modes;
	}

	public int getCount() {
		return modes.size();
	}

	public Object getItem(int position) {
		return modes.get(position);
	}

	public long getItemId(int position) {
		return position;
	}
	
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		if(convertView == null) {
			convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.simple_list_item_single_choice, null);
			holder = new ViewHolder();
			holder.tv_mode = (TextView) convertView.findViewById(R.id.tv_mode);
			holder.radioButton = (RadioButton) convertView.findViewById(R.id.radioButton);
			convertView.setTag(holder);
		}
		else {
			holder = (ViewHolder) convertView.getTag();
		}
		holder.tv_mode.setText(modes.get(position).get("mode").toString());
		holder.radioButton.setChecked((Boolean) modes.get(position).get("checked"));
		holder.radioButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				if(position != selectedItemPos) {
					setSelectedItemPos(position);
					resetCheckedItem(position);
				}
			}
		});
		return convertView;
	}
	
	private void resetCheckedItem(int position) {
		for(int i = 0; i < modes.size(); i++) {
			if(i == position) {
				modes.get(i).put("checked", true);
			}
			else {
				modes.get(i).put("checked", false);
			}
		}
		notifyDataSetChanged();
	}

	class ViewHolder {
		TextView tv_mode;
		RadioButton radioButton;
	}

}
